package ice;

import com.alibaba.fastjson.JSONObject;
import ice.util.tools;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.regex.Pattern;
/*
 * 作者：icefield
 * 时间：2021/3/22
 * 描述：程序启动的时候要做的事
 */

public class Main extends Application {

    public static Stage stage;
    public static String sqlmapPath=null;


    public static Main main;
    private static File startapiFile;
    public static String OSname=null;  //操作系统类型
    static{
        String osName = System.getProperty("os.name"); //获取指定键（即os.name）的系统属性,如：Windows 7。

        if (Pattern.matches("Linux.*", osName)) {
            OSname="Linux";
            startapiFile = new File(System.getProperty("user.home")+"/startapi.sh");
        } else if (Pattern.matches("Windows.*", osName)) {
            OSname="Windows";
            startapiFile = new File(System.getProperty("user.home")+"/startapi.bat");
        } else if (Pattern.matches("Mac.*", osName)) {
            OSname="Mac";
        }
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        Platform.exit();
        System.exit(0);
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("fxml/loadPage.fxml"));
        primaryStage.setTitle("SQLI");
        primaryStage.setScene(new Scene(root, 400, 275));
        primaryStage.initStyle(StageStyle.UNDECORATED);
        primaryStage.show();
        startSqlmapapi(primaryStage);
        showMainStage();

        primaryStage.close();

        /*
         *  作者：icefield
         *  说明：开启一个线程，每一分钟检测一次服务器连接（即黑窗口是否开着）若关闭了则退出程序
         */
        new Thread(() -> {
            boolean flag=true;
            while (flag){
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                flag=isonline();
            }
//            System.out.println("连接超时");
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    Alert al = new Alert(Alert.AlertType.WARNING);
                    al.setContentText("失去sqlmapapi服务端连接，程序即将退出");
                    al.showAndWait();
                    Platform.exit();
                    System.exit(0);
                }
            });
        }).start();

    }

/*
    检测服务器端是否正常开启
 */
    public boolean isonline(){
        Socket socket = new Socket();
        try {
            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8775);
            socket.connect(address,1000);
            /*
             *  作者：icefield
             *  说明：不关闭socket会卡住server
             */
            socket.close();
            return true;
        } catch (IOException e) {
            System.out.println("连接超时");
        }
        return false;
    }

    /*
     *  作者：icefield
     *  说明：启动SQLmapapi服务器端
     */
    private void startSqlmapapi(Stage primaryStage) {
        BufferedReader bufferedReader=null;
        /*
         *  作者：icefield
         *  说明：配置文件，用户目录下的peizhi.json
         */

        while (sqlmapPath == null) {
            sqlmapPath= 初始化配置文件(primaryStage,startapiFile);
        }

    }

    /*
     * 作者：icefield
     * 说明：启动主界面
     */
    private void showMainStage() {
        try {
            Parent mainstage = FXMLLoader.load(getClass().getResource("fxml/mainStage.fxml"));
            stage = new Stage();
            stage.setMinWidth(750);
            stage.setMinHeight(750);

            stage.setScene(new Scene(mainstage));
            stage.getIcons().add(new Image(getClass().getResourceAsStream("/ice/resource/cool.png")));
            stage.setTitle("SQL注入测试工具");
            stage.getScene().getStylesheets().add(getClass().getClassLoader().getResource("ice/resource/abc.css").toString());
            stage.show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String 初始化配置文件(Stage primaryStage, File startapiFile) {
        String readjson = "";
        BufferedReader bufferedReader=null;
        String sqlmapPath=null;
        File jsonFile = new File(System.getProperty("user.home")+"/peizhi.json");
        try {
            if(jsonFile.exists()){
                FileInputStream fileInputStream = new FileInputStream(jsonFile);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
                bufferedReader=new BufferedReader(inputStreamReader);
                String tempString=null;
                while((tempString=bufferedReader.readLine())!=null){
                    readjson+=tempString;
                }
                JSONObject jsonObject = JSONObject.parseObject(readjson);
                sqlmapPath = jsonObject.getString("sqlmapPath");
                fileInputStream.close();
            }else{
                DirectoryChooser directoryChooser = new DirectoryChooser();
                directoryChooser.setTitle("选择SQLmap路径");
                directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("请选择SQLmap主目录");
                alert.showAndWait();
                File sqlmap = directoryChooser.showDialog(primaryStage);
                /*
                 *  作者：icefield
                 *  说明：若没选择目录，返回空
                 */
                if(null==sqlmap){
                    tools.提醒弹窗("请选择正确的目录！");
                    return null;
                }
                sqlmapPath = sqlmap.getPath();
                String apipath = sqlmapPath + "/sqlmapapi.py";
                File apiFile = new File(apipath);
                if (!apiFile.exists()){
                    tools.提醒弹窗("选择错误的路径，请重新选择！");
                    return null;
                }
                /*
                 *  作者：icefield
                 *  说明：写配置文件
                 */
                jsonFile.createNewFile();
                String str="{\n" +
                        "  \"version\": \"1.0\",\n" +
                        "  \"zuozhe\": \"icefiled\"\n" +
                        "}";
                JSONObject jo = JSONObject.parseObject(str);
                jo.put("sqlmapPath",sqlmapPath);
                tools.写配置文件(jsonFile,jo.toJSONString());

                String cmd = null;

                if (Main.OSname.equals("Windows")){
                    cmd = "python " + apipath + " -s";
                } else if(Main.OSname.equals("Linux")){
                    cmd = "#!/bin/bash\npython " + apipath + " -s";
                }

                if (!startapiFile.exists()) {
                    startapiFile.createNewFile();
                }
                OutputStreamWriter writer2 = new OutputStreamWriter(new FileOutputStream(startapiFile, false), "UTF-8");
                writer2.write(cmd);
                writer2.close();
            }
            tools.提醒弹窗("请不要关闭黑窗口！！!");

            if (Main.OSname.equals("Windows")){
                Runtime.getRuntime().exec("cmd /c start " + System.getProperty("user.home") + "/startapi.bat");
            } else if(Main.OSname.equals("Linux")){
                Runtime.getRuntime().exec("sh " + System.getProperty("user.home") + "/startapi.sh");
            }
            return sqlmapPath;
        } catch (Exception e) {
            return null;
        }
    }


    public static void main(String[] args) {
        launch(args);
    }

    public static String getSqlmapPath() {
        return sqlmapPath;
    }

    public Main() {
        super();
        main=this;
    }
}
